import { defineStore } from "pinia";
import request from "@/utils/request";
import message from "@/utils/message";
import { UserInfo } from "@/types/user";
import { RequestParams } from "@/types/request";
import api from "@/utils/api";
import { AxiosRequestHeaders } from "axios";

export const useUserStore = defineStore("userStore", {
  state: (): {
    userInfo: UserInfo;
  } => ({
    userInfo: {} as UserInfo,
  }),
  actions: {
    async login(loginParams: RequestParams) {
      try {
        let result: any = await request({
          method: "post",
          url: api.usersLogin,
          data: loginParams as RequestParams,
          headers: {
            "Content-Type": "application/json",
          } as AxiosRequestHeaders,
        });
        if (!result) {
          return;
        }
        if (result.code === 1) {
          this.userInfo = result.data;
          message.success("登录成功");
          let userData: UserInfo = {} as UserInfo;
          userData = result.data;
          sessionStorage.setItem("userData", JSON.stringify(userData));
          return result;
        } else {
          message.error("登陆失败，请检查帐号或密码");
        }
      } catch (error) {
        message.error("登陆失败，请检查帐号或密码");
      }
    },
    async register(registerParams: RequestParams) {
      try {
        let result: any = await request({
          method: "post",
          url: api.usersRegister,
          data: registerParams as RequestParams,
          headers: {
            "Content-Type": "application/json",
          } as AxiosRequestHeaders,
        });
        if (!result) {
          return;
        }
        if (result.code === 1) {
          message.success("注册成功");
          //存一下信息，跳转登录不用输入
          this.userInfo = registerParams as UserInfo;
          return result;
        } else {
          message.error("注册失败，请检查相关信息");
        }
      } catch (error) {
        message.error("注册失败，请检查相关信息");
      }
    },
    getUserData() {
      const sessionData: any = sessionStorage.getItem("userData");
      const userData: UserInfo = JSON.parse(sessionData);
      this.userInfo = userData;
      return this.userInfo;
    },
    setUserData(userInfo: UserInfo) {
      this.userInfo = userInfo;
    },
    clearUserData() {
      this.userInfo = {
        userId: -1,
        username: "",
        token: "",
        email: "",
        role: "HEALTHCARE",
      };
      sessionStorage.removeItem("userData");
    },
  },
});
